package com.ipay.wechat.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.ipay.utils.StringUtil;
import com.ipay.wechat.service.TradeRecordService;
import com.ipay.wechat.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ipay.wechat.dao.UserWechatInfoDao;
import com.ipay.wechat.pojo.UserWechatInfo;
import com.ipay.wechat.service.UserWechatInfoService;
import com.ipay.wechat.util.ExecuteWeChat;

import net.sf.json.JSONObject;

@Service("uwiService")
public class UserWechatInfoServiceImpl implements UserWechatInfoService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private TradeRecordService tradeRecordService;
    @Autowired
    private UserWechatInfoDao wechatInfoDao;


    @Override
    public int findCountOneWXUI(String openid) {
        logger.info("openid===" + openid);
        return wechatInfoDao.findCountOneWXUI(openid);
    }

    @Override
    public void addWechatUserInfo(UserWechatInfo userWechatInfo) {
        /*UserWechatInfo userWechatInfo = new UserWechatInfo();
        userWechatInfo.setOpenid(jObject.getString("openid"));
		userWechatInfo.setCity(jObject.getString("city"));
		userWechatInfo.setCountry(jObject.getString("country"));
		userWechatInfo.setProvince(jObject.getString("province"));
		userWechatInfo.setHeadimgurl(jObject.getString("headimgurl"));
		userWechatInfo.setNickname(URLEncoder.encode(jObject.getString("nickname")));
		userWechatInfo.setSex(jObject.getString("sex"));
		userWechatInfo.setSubscribe(Integer.parseInt(jObject.getString("subscribe")));
		SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss");
		try {
			userWechatInfo.setSubscribe_time(formatter.parse(jObject.getString("subscribe_time")));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
        wechatInfoDao.addWechatUserInfo(userWechatInfo);
    }

    @Override
    public void updateWechatUserInfo(UserWechatInfo userWechatInfo) {
        wechatInfoDao.updateWechatUserInfo(userWechatInfo);
    }

    @Override
    public UserWechatInfo findOneByOpenidInUserWX(String openid) {
        return wechatInfoDao.findOneByOpenidInUserWX(openid);
    }


    /**
     * 通过微信Openid获取 微信用户信息
     *
     * @param openid
     * @return
     * @throws ParseException
     * zhenliu  2017-09-20
     */
    @Override
    public UserWechatInfo gainUserWechatInfo(String openid) {
        UserWechatInfo userWechatInfo = new UserWechatInfo();
        if(StringUtil.isNotEmpty(openid)) {
            String access_token = tradeRecordService.getAccessToken();
            logger.info("openid====【" + openid + "】access_token====【" + access_token + "】");
            String result = ExecuteWeChat.getBaseUserInfo(access_token, openid); // 获取用户的微信信息
            logger.info("根据access_token获取用户信息====【" + result + "】");
            if (StringUtil.isNotEmpty(result)) {
                JSONObject json = JSONObject.fromObject(result);
                int i = 0;
                while (i < 5 && (json.containsKey("errcode") || (StringUtil.isNotEmpty(json.get("errcode")) && json.get("errcode").equals("40013")))) {
                    access_token = tradeRecordService.freshAccessToken();//重新获取accessToken
                    logger.info("再次openid====【" + openid + "】access_token====【" + access_token + "】");
                    result = ExecuteWeChat.getBaseUserInfo(access_token, openid); // 获取用户的微信信息
                    logger.info("再次根据access_token获取用户信息====【" + result + "】");
                    if (StringUtil.isNotEmpty(result)) {
                        json = JSONObject.fromObject(result);
                    }
                    i++;
                }
                userWechatInfo.setOpenid(openid);
                userWechatInfo.setSubscribe(Integer.valueOf(StringUtil.isNotEmptyValue(json.get("subscribe"), "0").toString()));
                String nickname = StringUtil.isNotEmptyValue(json,"nickname", "").toString();
                userWechatInfo.setNickname(StringUtil.filterEmoji(nickname));
                userWechatInfo.setSex(StringUtil.isNotEmptyValue(json,"sex", "0").toString());
                userWechatInfo.setProvince(StringUtil.isNotEmptyValue(json,"province", "").toString());
                userWechatInfo.setCity(StringUtil.isNotEmptyValue(json,"city", "").toString());
                userWechatInfo.setCountry(StringUtil.isNotEmptyValue(json,"country", "").toString());
                userWechatInfo.setHeadimgurl(StringUtil.isNotEmptyValue(json,"headimgurl", "").toString());
                try {
                    if (json.has("subscribe_time")) {
                        if (StringUtil.isNotEmpty(json.getString("subscribe_time"))) {
                            Date orderDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(Utils.stampToDate(json.getString("subscribe_time")));
                            userWechatInfo.setSubscribe_time(orderDate);
                        }
                    }
                } catch (ParseException e) {
                    logger.error("日期处理异常", e);
                }
                userWechatInfo.setRemark(StringUtil.isNotEmptyValue(json,"remark", "").toString());
                userWechatInfo.setGroupid(Integer.valueOf(StringUtil.isNotEmptyValue(json,"groupid", "0").toString()));
            }
        }
        return userWechatInfo;
    }
}
